package com.xiang.community.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiang.community.dao.MessageMapper;
import com.xiang.community.dto.MessageCountDTO;
import com.xiang.community.entity.Message;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class MessageService {

    @Resource
    private MessageMapper messageMapper;

    public int addMessage(Message message) {
        message.setContent(HtmlUtils.htmlEscape(message.getContent()));
        return messageMapper.insertMessage(message);
    }

    public int readMessage(List<Integer> ids, int userId) {
        return messageMapper.updateStatus(ids, 1, userId);
    }

    public PageInfo<Message> findConversationsWithPage(int userId, String messageType, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Message> list = messageMapper.selectConversations(userId, messageType);
        PageInfo<Message> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    public PageInfo<Message> getMessageList(String conversationId, int pageNum, int pageSize, int userId) {
        PageHelper.startPage(pageNum, pageSize);
        List<Message> list = messageMapper.getMessages(conversationId, userId);
        return new PageInfo<>(list);
    }

    public MessageCountDTO countMessage(String conversationId, int userId) {
        return messageMapper.countMessage(conversationId, userId);
    }

    public int getUnreadConversationCount(int id) {
        return messageMapper.getUnreadConversationCount(id);
    }

    public void updateMessageStatus(List<Integer> ids, int status, int userId) {
        messageMapper.updateStatus(ids, status, userId);
    }

    public PageInfo<Message> findSystemMessageWithPage(int userId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Message> list = messageMapper.selectSystemMessage(userId);
        return new PageInfo<>(list);
    }

    public Message getMessage(Integer messageId, Integer userId) {
        return messageMapper.getMessage(messageId, userId);
    }

    public void deleteConverstion(String id, Integer userId) {
        messageMapper.deleteConversation(id, userId);
    }

    public int getUnreadSystemMessageCount(int id) {
        return messageMapper.countUnreadSystemMessage(id);
    }

    public int getToId(String conversationId, int userId) {
        Message message = messageMapper.getLastMessage(conversationId, userId);
        if (userId == message.getFromId()) {
            return message.getToId();
        }
        return message.getFromId();
    }
}
